package dataflow.core;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ExecutorService;

import org.apache.log4j.Logger;


public class TaskExecutionEvent implements ExecutionEvent, Runnable {

	private Logger log = Logger.getLogger(TaskExecutionEvent.class);
	
	private final Method method;
	private final Object sourceInstance;
	private final int portset;
	private final Task task;
	
	public TaskExecutionEvent(Method method, Object sourceInstance, int portset, Task task) {
		this.method = method;
		this.portset = portset;
		this.sourceInstance = sourceInstance;
		this.task = task;
	}
	
	@Override
	public void execute(ExecutionEventParser executionEventParser, ExecutorService threadExecutor) {
		threadExecutor.submit(this);
	}

	@Override
	public void run() {
		Integer returnPortset = -1;
		try{
			returnPortset = (Integer)method.invoke(sourceInstance, portset);
		} catch (InvocationTargetException ite){
			log.error("Invocation of main method failed.", ite);
		} catch (IllegalAccessException iae){
			log.error("Method '" + method.getName() + "' have to be public.",iae);
		} catch (Exception e){
			log.error("Unknown error while executing core of '" + task.getETask().getName() + "'.");
		} finally {
			task.receiveResult(returnPortset);
		}
		
	}

}
